<template>
  <view class="verification-page">
    <!-- 导航栏 -->
    <up-navbar :title="useT('身份认证')" :safeAreaInsetTop="true" :autoBack="true" leftIconColor="#333" titleColor="#333" bgColor="#fff" placeholder></up-navbar>

    <!-- 步骤指示器 -->
    <view class="step-indicator">
      <view class="step-item" :class="{ active: currentStep === 1, completed: currentStep > 1 }">
        <view class="step-number">1</view>
        <view class="step-text">{{ useT('填写信息') }}</view>
      </view>
      <view class="step-line" :class="{ active: currentStep > 1 }"></view>
      <view class="step-item" :class="{ active: currentStep === 2 }">
        <view class="step-number">2</view>
        <view class="step-text">{{ useT('上传证件') }}</view>
      </view>
    </view>

    <!-- 第一步：填写信息 -->
    <view v-if="currentStep === 1" class="step-content">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <up-loading-icon mode="circle" color="#12c284"></up-loading-icon>
        <view class="loading-text">{{ useT('加载中.') }}</view>
      </view>

      <!-- 表单内容 -->
      <view v-else class="form-container">
        <!-- 国家/地区 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            {{ useT('国家/地区') }}
          </view>
          <view class="form-input" @click="showCountryPicker">
            <text :class="{ placeholder: !formData.country_region }">{{ useT(formData.country_region) || useT('请选择国家/地区') }}</text>
            <up-icon name="arrow-down" size="24" color="#999"></up-icon>
          </view>
        </view>

        <!-- 证件类型 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            {{ useT('证件类型') }}
          </view>
          <view class="form-input" @click="showIdTypePicker">
            <text :class="{ placeholder: !formData.id_type }">{{ getIdTypeText(formData.id_type) || useT('请选择证件类型') }}</text>
            <up-icon name="arrow-down" size="24" color="#999"></up-icon>
          </view>
        </view>

        <!-- 证件号码 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            {{ useT('证件号码') }}
          </view>
          <up-input v-model="formData.id_number" :placeholder="useT('请输入证件号码')" :clearable="true" class="form-input-field"></up-input>
        </view>

        <!-- 姓名 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            {{ useT('姓名') }}
          </view>
          <up-input v-model="formData.full_name" :placeholder="useT('请输入姓名')" :clearable="true" class="form-input-field"></up-input>
        </view>
      </view>

      <!-- 下一步按钮 -->
      <view v-if="!loading" class="next-button" @click="nextStep">
        {{ useT('下一步') }}
      </view>
    </view>

    <!-- 第二步：上传证件 -->
    <view v-if="currentStep === 2" class="step-content">
      <view class="upload-container">
        <!-- 温馨提示 -->
        <view class="tips-box">
          <view class="tips-title">{{ useT('温馨提示') }}</view>
          <view class="tips-content">
            <view class="tips-item">{{ useT('请确保资料填写和即将上传的证件一致,否则将被驳回。') }}</view>
            <view class="tips-item">{{ useT('请上传清晰的证件照片,必须能看清证件号码和姓名。') }}</view>
          </view>
        </view>

        <!-- 照片质量示例 -->
        <view class="photo-examples">
          <view class="example-item">
            <view class="example-icon success">✓</view>
            <view class="example-text">{{ useT('标准') }}</view>
          </view>
          <view class="example-item">
            <view class="example-icon error">✗</view>
            <view class="example-text">{{ useT('边框缺失') }}</view>
          </view>
          <view class="example-item">
            <view class="example-icon error">✗</view>
            <view class="example-text">{{ useT('照片模糊') }}</view>
          </view>
          <view class="example-item">
            <view class="example-icon error">✗</view>
            <view class="example-text">{{ useT('反光遮挡') }}</view>
          </view>
        </view>

        <!-- 上传区域 -->
        <view class="upload-section">
          <!-- 正面照 -->
          <view class="upload-item">
            <view class="upload-title">{{ useT('正面照') }}</view>
            <view class="upload-subtitle">{{ useT('上传您的证件正面') }}</view>
            <view class="upload-area" @click="uploadImage('front')">
              <image v-if="formData.id_front_image" :src="formData.id_front_image" class="uploaded-image" mode="aspectFit"></image>
              <view v-else class="upload-placeholder">
                <up-icon name="camera" size="48" color="#12c284"></up-icon>
              </view>
            </view>
          </view>

          <!-- 国徽照 -->
          <view class="upload-item">
            <view class="upload-title">{{ useT('反面照') }}</view>
            <view class="upload-subtitle">{{ useT('上传您的证件反面') }}</view>
            <view class="upload-area" @click="uploadImage('back')">
              <image v-if="formData.id_back_image" :src="formData.id_back_image" class="uploaded-image" mode="aspectFit"></image>
              <view v-else class="upload-placeholder">
                <up-icon name="camera" size="48" color="#12c284"></up-icon>
              </view>
            </view>
          </view>

          <!-- 手持证件照 -->
          <view class="upload-item">
            <view class="upload-title">{{ useT('手持证件照') }}</view>
            <view class="upload-subtitle">{{ useT('上传您的手持证件照') }}</view>
            <view class="upload-note">{{ useT('注意手臂露出、拍摄清晰') }}</view>
            <view class="upload-area" @click="uploadImage('handheld')">
              <image v-if="formData.id_handheld_image" :src="formData.id_handheld_image" class="uploaded-image" mode="aspectFit"></image>
              <view v-else class="upload-placeholder">
                <up-icon name="camera" size="48" color="#12c284"></up-icon>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 按钮组 -->
      <view class="button-group">
        <!-- 上一步按钮 -->
        <view class="prev-button" @click="prevStep">
          {{ useT('上一步') }}
        </view>
        <!-- 确定按钮 -->
        <view class="submit-button" @click="submitVerification">
          {{ useT('确定') }}
        </view>
      </view>
    </view>

    <!-- 国家/地区选择器 -->
    <up-picker :show="showCountryPickerFlag" :columns="[countryColumns]" keyName="text" valueName="value" :cancelText="useT('取消')" :confirmText="useT('确定')" @confirm="onCountryConfirm" @cancel="showCountryPickerFlag = false"></up-picker>

    <!-- 证件类型选择器 -->
    <up-picker :show="showIdTypePickerFlag" :columns="[idTypeColumns]" keyName="text" valueName="value" :cancelText="useT('取消')" :confirmText="useT('确定')" @confirm="onIdTypeConfirm" @cancel="showIdTypePickerFlag = false"></up-picker>
  </view>
</template>

<script setup>
import { uploadImage as uploadImageApi } from '@/api/common.js';
import { getIdentityVerification, submitIdentityVerification } from '@/api/user.js';
import { COUNTRY_CODES, DEFAULT_COUNTRY_CODE, getCountryByCode } from '@/config/countryCodes.js';
import { useT } from '@/utils/i18n.js';
import { onMounted, reactive, ref } from 'vue';

// 当前步骤
const currentStep = ref(1);

// 加载状态
const loading = ref(false);

// 表单数据
const formData = reactive({
  country_region: getCountryByCode(DEFAULT_COUNTRY_CODE).name, // 设置默认国家
  id_type: '',
  id_number: '',
  full_name: '',
  id_front_image: '',
  id_back_image: '',
  id_handheld_image: ''
});

// 选择器状态
const showCountryPickerFlag = ref(false);
const showIdTypePickerFlag = ref(false);

// 国家/地区选项 - 使用countryCodes.js中的数据
const countryColumns = ref(
  COUNTRY_CODES.map((country) => ({
    text: useT(country.name),
    value: useT(country.name),
    countryCode: country.countryCode,
    code: country.code
  }))
);

// 证件类型选项
const idTypeColumns = ref([
  // { text: useT('身份证'), value: '1' },
  { text: useT('护照'), value: '2' }
  // { text: useT('驾驶证'), value: '3' },
  // { text: useT('其他'), value: '4' }
]);

// 显示国家/地区选择器
const showCountryPicker = () => {
  showCountryPickerFlag.value = true;
};

// 显示证件类型选择器
const showIdTypePicker = () => {
  showIdTypePickerFlag.value = true;
};

// 国家/地区确认
const onCountryConfirm = (e) => {
  const selectedCountry = e.value[0];
  formData.country_region = selectedCountry.value;
  showCountryPickerFlag.value = false;
};

// 证件类型确认
const onIdTypeConfirm = (e) => {
  formData.id_type = e.value[0].value;
  showIdTypePickerFlag.value = false;
};

// 获取证件类型文本
const getIdTypeText = (value) => {
  const item = idTypeColumns.value.find((item) => item.value === value);
  return useT(item ? item.text : '');
};

// 获取用户认证资料
const getUserVerificationData = async () => {
  try {
    loading.value = true;
    const res = await getIdentityVerification();

    if (res.status === 200 && res.data) {
      const data = res.data;

      // 回显表单数据
      if (data.country_region) {
        formData.country_region = data.country_region;
      }
      if (data.id_type) {
        formData.id_type = data.id_type;
      }
      if (data.id_number) {
        formData.id_number = data.id_number;
      }
      if (data.full_name) {
        formData.full_name = data.full_name;
      }
      if (data.id_front_image) {
        formData.id_front_image = data.id_front_image;
      }
      if (data.id_back_image) {
        formData.id_back_image = data.id_back_image;
      }
      if (data.id_handheld_image) {
        formData.id_handheld_image = data.id_handheld_image;
      }

      // 如果所有必填信息都已填写，直接进入第二步
      if (data.country_region && data.id_type && data.id_number && data.full_name) {
        currentStep.value = 2;
      }
    }
  } catch (error) {
    console.error('获取认证资料失败:', error);
    uni.showToast({
      title: error.message || useT('获取资料失败'),
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取用户认证资料
onMounted(() => {
  getUserVerificationData();
});

// 上一步
const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--;
  }
};

// 下一步
const nextStep = () => {
  // 验证必填字段
  if (!formData.country_region) {
    uni.showToast({
      title: useT('请选择国家/地区'),
      icon: 'none'
    });
    return;
  }
  if (!formData.id_type) {
    uni.showToast({
      title: useT('请选择证件类型'),
      icon: 'none'
    });
    return;
  }
  if (!formData.id_number) {
    uni.showToast({
      title: useT('请输入证件号码'),
      icon: 'none'
    });
    return;
  }
  if (!formData.full_name) {
    uni.showToast({
      title: useT('请输入姓名'),
      icon: 'none'
    });
    return;
  }

  currentStep.value = 2;
};

// 上传图片
const uploadImage = async (type) => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    });
    console.log('====>res', res);
    if (res.tempFilePaths && res.tempFilePaths.length > 0) {
      const tempFilePath = res.tempFilePaths[0];

      // 显示上传进度
      uni.showLoading({
        title: useT('上传中.')
      });

      // 生成文件名
      const timestamp = Date.now();
      const filename = `${type}_${timestamp}.jpg`;

      // 调用上传接口
      const uploadRes = await uploadImageApi({
        filename,
        filePath: tempFilePath,
        name: 'file'
      });

      if (uploadRes.status === 200) {
        // 根据类型设置对应的图片字段
        if (type === 'front') {
          formData.id_front_image = uploadRes.data.url;
        } else if (type === 'back') {
          formData.id_back_image = uploadRes.data.url;
        } else if (type === 'handheld') {
          formData.id_handheld_image = uploadRes.data.url;
        }

        uni.hideLoading();
        uni.showToast({
          title: useT('上传成功'),
          icon: 'success'
        });
      } else {
        throw new Error(uploadRes.message || useT('上传失败'));
      }
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || error || useT('上传失败'),
      icon: 'none'
    });
  }
};

// 提交认证
const submitVerification = async () => {
  // 验证图片是否已上传
  if (!formData.id_front_image) {
    uni.showToast({
      title: useT('请上传正面照'),
      icon: 'none'
    });
    return;
  }
  if (!formData.id_back_image) {
    uni.showToast({
      title: useT('请上传反面照'),
      icon: 'none'
    });
    return;
  }
  if (!formData.id_handheld_image) {
    uni.showToast({
      title: useT('请上传手持证件照'),
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({
      title: useT('提交中.')
    });

    // 获取选中国家的国家代码
    const selectedCountry = countryColumns.value.find((country) => country.value === formData.country_region);
    const params = {
      country_region: formData.country_region,
      country_code: selectedCountry?.countryCode || 'CN', // 添加国家代码
      id_type: formData.id_type,
      id_number: formData.id_number,
      full_name: formData.full_name,
      id_front_image: formData.id_front_image,
      id_back_image: formData.id_back_image,
      id_handheld_image: formData.id_handheld_image
    };

    const res = await submitIdentityVerification(params);

    uni.hideLoading();

    if (res.status === 200) {
      uni.showToast({
        title: useT('提交成功'),
        icon: 'success'
      });

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.message || useT('提交失败'),
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || useT('提交失败'),
      icon: 'none'
    });
  }
};
</script>

<style lang="scss" scoped>
.verification-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.step-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  background-color: #fff;

  .step-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    .step-number {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      background-color: #e0e0e0;
      color: #999;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      font-weight: 600;
      margin-bottom: 10rpx;
    }

    .step-text {
      font-size: 24rpx;
      color: #999;
    }

    &.active {
      .step-number {
        background-color: #12c284;
        color: #fff;
      }
      .step-text {
        color: #12c284;
      }
    }

    &.completed {
      .step-number {
        background-color: #12c284;
        color: #fff;
      }
      .step-text {
        color: #12c284;
      }
    }
  }

  .step-line {
    width: 100rpx;
    height: 4rpx;
    background-color: #e0e0e0;
    margin: 0 20rpx;

    &.active {
      background-color: #12c284;
    }
  }
}

.step-content {
  flex: 1;
  padding: 0 40rpx 120rpx;
}

// 加载状态样式
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  background-color: #fff;
  border-radius: 20rpx;

  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #666;
  }
}

.form-container {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 40rpx;

  &:last-child {
    margin-bottom: 0;
  }

  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;

    .required {
      color: #ff4757;
      margin-right: 8rpx;
    }
  }

  .form-input {
    height: 88rpx;
    background-color: #f8f8f8;
    border-radius: 12rpx;
    padding: 0 24rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .placeholder {
      color: #999;
    }
  }

  .form-input-field {
    height: 88rpx;
    background-color: #f8f8f8;
    border-radius: 12rpx;
  }
}

.button-group {
  display: flex;
  margin-top: 40rpx;
}

.prev-button {
  flex: 1;
  height: 88rpx;
  background: #f5f5f5;
  color: #666;
  font-size: 32rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 44rpx;
  margin-right: 20rpx;
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    background: #e8e8e8;
  }
}

.next-button,
.submit-button {
  flex: 1;
  height: 88rpx;
  background: linear-gradient(135deg, #12c284, #0fa870);
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 44rpx;
  box-shadow: 0 8rpx 24rpx rgba(18, 194, 132, 0.3);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 12rpx rgba(18, 194, 132, 0.4);
  }
}

.upload-container {
  .tips-box {
    background-color: #e3f2fd;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 40rpx;

    .tips-title {
      font-size: 28rpx;
      font-weight: 600;
      color: #1976d2;
      margin-bottom: 16rpx;
    }

    .tips-content {
      .tips-item {
        font-size: 24rpx;
        color: #1976d2;
        line-height: 1.6;
        margin-bottom: 8rpx;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  .photo-examples {
    display: flex;
    justify-content: space-between;
    margin-bottom: 40rpx;

    .example-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      flex: 1;

      .example-icon {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        font-weight: 600;
        margin-bottom: 12rpx;

        &.success {
          background-color: #4caf50;
          color: #fff;
        }

        &.error {
          background-color: #f44336;
          color: #fff;
        }
      }

      .example-text {
        font-size: 20rpx;
        color: #666;
        text-align: center;
      }
    }
  }

  .upload-section {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 40rpx;

    .upload-item {
      margin-bottom: 60rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .upload-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 12rpx;
      }

      .upload-subtitle {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 8rpx;
      }

      .upload-note {
        font-size: 22rpx;
        color: #999;
        margin-bottom: 20rpx;
      }

      .upload-area {
        width: 100%;
        height: 400rpx;
        border: 2rpx dashed #ddd;
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        overflow: hidden;

        .uploaded-image {
          width: 100%;
          height: 100%;
        }

        .upload-placeholder {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }
}
</style>
